package com.yiren.dbaa.view.adapter;

import android.content.Context;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.DeviceStudyConfigBean;
import com.yiren.backstage.currency.bean.CarStateBean;
import com.yiren.dbaa.R;
import com.yiren.dbaa.module.param_config.api.ParamConfigApi;
import com.yiren.dbaa.view.dialog.CustomDialog;
import com.yiren.dbaa.view.toast.MessageBox;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 类描述：   档位矫正适配器
 */
public class GearCorrectAdapter extends BaseAdapter {

    private Context context;

    /**
     * 档位校正值
     */
    private float gearOneStartValue;
    private float gearOneEndValue;
    private float gearTwoStartValue;
    private float gearTwoEndValue;
    private float gearThreeStartValue;
    private float gearThreeEndValue;
    private float gearFourStartValue;
    private float gearFourEndValue;
    private float gearFiveStartValue;
    private float gearFiveEndValue;

    private float minGearLevelValue = 0; //保存档位比最小值
    private float maxGearLevelValue = 0; //保存档位比最大值
    private Button btCurrentGear;        //当前档位学习按钮

    private Handler gearLevelHandler;
    private Runnable gearLevelRunnable;

    public GearCorrectAdapter(Context mContext) {
        this.context = mContext;
        getGearValue();
    }

    /**
     * 获取档位校正值
     */
    public void getGearValue() {
        Map<Integer, float[]> cbdMap = LoadConfigApi.loadDeviceStudyConfig(context).getCdbMap();
        gearOneStartValue = cbdMap.get(1)[0];
        gearOneEndValue = cbdMap.get(1)[1];
        gearTwoStartValue = cbdMap.get(2)[0];
        gearTwoEndValue = cbdMap.get(2)[1];
        gearThreeStartValue = cbdMap.get(3)[0];
        gearThreeEndValue = cbdMap.get(3)[1];
        gearFourStartValue = cbdMap.get(4)[0];
        gearFourEndValue = cbdMap.get(4)[1];
        gearFiveStartValue = cbdMap.get(5)[0];
        gearFiveEndValue = cbdMap.get(5)[1];
    }

    public void save() {
        DeviceStudyConfigBean deviceStudyConfig = LoadConfigApi.loadDeviceStudyConfig(context);
        //传动比
        Map<Integer, float[]> cbdMap = deviceStudyConfig.getCdbMap();
        cbdMap.put(1, new float[]{gearOneStartValue, gearOneEndValue});
        cbdMap.put(2, new float[]{gearTwoStartValue, gearTwoEndValue});
        cbdMap.put(3, new float[]{gearThreeStartValue, gearThreeEndValue});
        cbdMap.put(4, new float[]{gearFourStartValue, gearFourEndValue});
        cbdMap.put(5, new float[]{gearFiveStartValue, gearFiveEndValue});
        deviceStudyConfig.setCdbMap(cbdMap);
        ParamConfigApi.saveDeviceStudyConfig(context, deviceStudyConfig);
    }

    @Override
    public int getCount() {
        return 5;
    }

    @Override
    public Object getItem(int arg0) {
        return null;
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_gear_collect, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.btGearStudy.setTag(20000);
        switch (position) {
            case 0:
                holder.tvGearRatio.setText(R.string.ump_onegearfix_text);
                holder.etGearStartRatio.setText(gearOneStartValue + "");
                holder.etGearEndRatio.setText(gearOneEndValue + "");
                break;
            case 1:
                holder.tvGearRatio.setText(R.string.ump_twogearfix_text);
                holder.etGearStartRatio.setText(gearTwoStartValue + "");
                holder.etGearEndRatio.setText(gearTwoEndValue + "");
                break;
            case 2:
                holder.tvGearRatio.setText(R.string.ump_threegearfix_text);
                holder.etGearStartRatio.setText(gearThreeStartValue + "");
                holder.etGearEndRatio.setText(gearThreeEndValue + "");
                break;
            case 3:
                holder.tvGearRatio.setText(R.string.ump_fourgearfix_text);
                holder.etGearStartRatio.setText(gearFourStartValue + "");
                holder.etGearEndRatio.setText(gearFourEndValue + "");
                break;
            case 4:
                holder.tvGearRatio.setText(R.string.ump_fivegearfix_text);
                holder.etGearStartRatio.setText(gearFiveStartValue + "");
                holder.etGearEndRatio.setText(gearFiveEndValue + "");
                break;
            default:
                break;
        }

        holder.etGearStartRatio.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")) return;
                switch (position) {
                    case 0:
                        gearOneStartValue = Float.valueOf(s.toString());
                        break;
                    case 1:
                        gearTwoStartValue = Float.valueOf(s.toString());
                        break;
                    case 2:
                        gearThreeStartValue = Float.valueOf(s.toString());
                        break;
                    case 3:
                        gearFourStartValue = Float.valueOf(s.toString());
                        break;
                    case 4:
                        gearFiveStartValue = Float.valueOf(s.toString());
                        break;
                    default:
                        break;
                }
            }
        });

        holder.etGearEndRatio.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")) return;
                switch (position) {
                    case 0:
                        gearOneEndValue = Float.valueOf(s.toString());
                        break;
                    case 1:
                        gearTwoEndValue = Float.valueOf(s.toString());
                        break;
                    case 2:
                        gearThreeEndValue = Float.valueOf(s.toString());
                        break;
                    case 3:
                        gearFourEndValue = Float.valueOf(s.toString());
                        break;
                    case 4:
                        gearFiveEndValue = Float.valueOf(s.toString());
                        break;
                    default:
                        break;
                }
            }
        });

        holder.btGearStudy.setOnClickListener(v -> {
            switch (Integer.parseInt(holder.btGearStudy.getTag().toString())) {
                case 20000:
                    showDialog(position, holder.btGearStudy);
                    break;
                case 20001:  //完成校正
                    endGearCorrect(position, holder.btGearStudy, holder.etGearStartRatio, holder.etGearEndRatio);
                    break;
                default:
                    break;
            }
        });
        return convertView;
    }

    public class ViewHolder {
        @BindView(R.id.tv_gear_ratio)
        TextView tvGearRatio;
        @BindView(R.id.et_gear_start_ratio)
        EditText etGearStartRatio;
        @BindView(R.id.et_gear_end_ratio)
        EditText etGearEndRatio;
        @BindView(R.id.bt_gear_study)
        Button btGearStudy;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    private void showDialog(int position, Button btGearStudy) {
        CustomDialog.Builder builder = new CustomDialog.Builder(context);
        builder.setTitle("温馨提示");
        builder.setMessage("挡位学习前请保持当前学习挡位怠速行驶状态,请勿踩离合，按语音提示进行操作。现在是怠速行驶状态吗？");
        builder.setPositiveButton("是", (dialog, which) -> {
            //开始校正
            startGearCorrect(position, btGearStudy);
            dialog.dismiss();
        });
        builder.setNegativeButton("否", (dialog, which) -> dialog.dismiss());
        builder.create().show();
    }

    /**
     * 当点击校正时启动线程，改变图片背景和字体
     */
    public void startGearCorrect(int position, Button btGearStudy) {
        if (CarStateBean.getInstance().getSpeed() < 3) {
            //如果车辆未启动，则语音提示
            MessageBox.VoiceModel(context, "请先启动车辆");
        } else {
            btGearStudy.setTag(20001);
            switch (position) {  //播报语音
                case 0:
                    MessageBox.VoiceModel(context, context.getString(R.string.one_and_two_gear_jz_message));
                    break;
                case 1:
                    MessageBox.VoiceModel(context, context.getString(R.string.one_and_two_gear_jz_message));
                    break;
                case 2:
                    MessageBox.VoiceModel(context, context.getString(R.string.three_and_four_gear_jz_message));
                    break;
                case 3:
                    MessageBox.VoiceModel(context, context.getString(R.string.three_and_four_gear_jz_message));
                    break;
                case 4:
                    MessageBox.VoiceModel(context, context.getString(R.string.five_gear_jz_message));
                    break;
                default:
                    break;
            }
            startHandlerGetGearLevel();
            btGearStudy.setClickable(false);
            btGearStudy.setText("正在学习");
            btCurrentGear = btGearStudy;
            btGearStudy.setTextColor(context.getResources().getColor(R.color.white));
            btGearStudy.setBackgroundResource(R.drawable.shape_dbaf_blue_corner5_soild_bg);
        }
    }

    /**
     * 开始校正线程方法，档位比值范围的获取
     */
    private void startHandlerGetGearLevel() {
        gearLevelHandler = new Handler();
        minGearLevelValue = 0;
        maxGearLevelValue = 0;
        final long startTime = System.currentTimeMillis();
        gearLevelRunnable = new Runnable() {
            @Override
            public void run() {
                // 获取档位比值
                float gearLevelValue = (float) CarStateBean.getInstance().getGearLevel();
                if (gearLevelValue > maxGearLevelValue) {  //获取档位比最大值
                    maxGearLevelValue = gearLevelValue;
                }
                if (minGearLevelValue == 0) {
                    minGearLevelValue = gearLevelValue;
                } else { //获取档位比最小值
                    if (gearLevelValue < minGearLevelValue) {
                        minGearLevelValue = gearLevelValue;
                    }
                }
                if (System.currentTimeMillis() - startTime < 30000) {
                    gearLevelHandler.postDelayed(this, 100);
                } else {
                    btCurrentGear.performClick();
                }
            }
        };
        gearLevelRunnable.run();
    }

    /**
     * 完成挡位校正
     */
    public void endGearCorrect(int position, Button btGearStudy, EditText etGearStartRatio, EditText etGearEndRatio) {
        btGearStudy.setText(R.string.ump_finish_fix);
        MessageBox.VoiceModel(context, context.getString(R.string.gear_jz_wc));
        btGearStudy.setBackgroundResource(R.drawable.shape_dbaf_gray_select_corner5_soild_bg);
        btGearStudy.setTextColor(context.getResources().getColor(R.color.white));
        //更改档位比值，在最小值档位比加2
        etGearStartRatio.setText(minGearLevelValue + "");
        //最大值档位比减2
        etGearEndRatio.setText(maxGearLevelValue + "");
        DeviceStudyConfigBean deviceStudyConfig = LoadConfigApi.loadDeviceStudyConfig(context);
        Map<Integer, float[]> cbdMap = deviceStudyConfig.getCdbMap();
        switch (position) {
            case 0:
                cbdMap.put(1, new float[]{gearOneStartValue, gearOneEndValue});
                break;
            case 1:
                cbdMap.put(2, new float[]{gearTwoStartValue, gearTwoEndValue});
                break;
            case 2:
                cbdMap.put(3, new float[]{gearThreeStartValue, gearThreeEndValue});
                break;
            case 3:
                cbdMap.put(4, new float[]{gearFourStartValue, gearFourEndValue});
                break;
            case 4:
                cbdMap.put(5, new float[]{gearFiveStartValue, gearFiveEndValue});
                break;
            default:
                break;
        }
        deviceStudyConfig.setCdbMap(cbdMap);
        ParamConfigApi.saveDeviceStudyConfig(context, deviceStudyConfig);
        //设置按钮无效
        btGearStudy.setClickable(false);
        //关闭线程
        gearLevelHandler.removeCallbacks(gearLevelRunnable);
        //当点击保存校正后，档位比最大和最小值归0
        minGearLevelValue = 0;
        maxGearLevelValue = 0;
    }

}
